package com.hrhr74.penguinstream.service.impl;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.hrhr74.penguinstream.constant.UserConstant;
import com.hrhr74.penguinstream.domain.dto.UserEditDTO;
import com.hrhr74.penguinstream.domain.po.User;
import com.hrhr74.penguinstream.service.UserEdit;
import com.hrhr74.penguinstream.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service(UserConstant.PASSWORD_EDIT)
public class UserEditPassword extends UserEdit {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Result editUser(UserEditDTO userEditDTO) {
        Long id = 1L;//TODO UserContext.getUser();
        if(userEditDTO == null){
            return Result.error("数据获取失败！");
        }

        if(userEditDTO.getPassword() == null || userEditDTO.getNewPassword() == null){
            return Result.error("请确认密码是否输入！");
        }

        String oldPassword = userEditDTO.getPassword();
        String newPassword = userEditDTO.getNewPassword();

        if(oldPassword.equals(newPassword)){
            return Result.error("新旧密码不能一样！");
        }
        User user = Db.lambdaQuery(User.class).eq(User::getId, id).one();
        if(!passwordEncoder.matches(oldPassword, user.getPassword())){
            return Result.error("旧密码输入错误！");
        }
        //修改密码
        String encode = passwordEncoder.encode(newPassword);
        boolean update = Db.lambdaUpdate(User.class).set(User::getPassword, encode).eq(User::getId, id).update();
        return update ? Result.ok("密码修改成功，请重新登录") : Result.error("密码修改失败");
    }
}
